
package com.tool;
 
import com.amazonaws.AmazonServiceException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.SDKGlobalConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
 
import java.io.File;
import java.nio.file.Paths;
 
/**
 * 类说明：JDYun oss
 */
public class JDYunOssTools {
 
    /** Access Key ID*/
    static final String accessKey = "5ABD430B2F0AF3F7720BCC30C499BAAE";
    /** Access Key Secret*/
    static final String secretKey = "2582D6E0C969864E89A2ABC513C17CB9";
    /** 上传地址*/
    static final String endpoint = "http://s3.cn-north-1.jdcloud-oss.com";
 
    /**
     * 方法说明：JDYun 上传
     * @author 小啊刚 2018-12-27 17:07
     */
    public static void JDYunUpload(String bucketName, String filePath) {
        try {
            String key = Paths.get(filePath).getFileName().toString();
            initS3().putObject(bucketName, key, new File(filePath));
            System.out.println("京东oss上传成功：" + filePath);
        } catch (AmazonServiceException e) {
            e.printStackTrace();
        }
    }
        
    /**
     * 方法说明：JDYun 删除
     * @author 小啊刚 2018-12-27 17:07
     */
    public static void JDYunDelete(String bucketName, String objectKey) {
        try {
            initS3().deleteObject(bucketName, objectKey);
            System.out.println("京东oss删除成功：" + objectKey);
        } catch (AmazonServiceException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 方法说明：初始化JDYun
    * @author 小啊刚 2018-12-27 17:04
     */
    public static AmazonS3 initS3() {
//        System.setProperty(SDKGlobalConfiguration.ENABLE_S3_SIGV4_SYSTEM_PROPERTY, "true");
        ClientConfiguration config = new ClientConfiguration();
 
        AwsClientBuilder.EndpointConfiguration endpointConfig = new AwsClientBuilder.EndpointConfiguration(endpoint, "cn-north-1");
        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
        AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);
 
        AmazonS3 s3 = AmazonS3Client.builder()
                .withEndpointConfiguration(endpointConfig)
                .withClientConfiguration(config)
                .withCredentials(awsCredentialsProvider)
                .disableChunkedEncoding()
                .withPathStyleAccessEnabled(true)
                .build();
        return s3;
    }
 
    public static void main(String[] args) {
        JDYunUpload("alikill-oss/test", "D:/test.png");
        //JDYunDelete("boom-oss/test", "1.jpg");
    }
}